//
//  DataBaseHelper.m
//  FMDB使用
//
//  Created by 檀志文 on 16/5/21.
//  Copyright © 2016年 ios檀志文. All rights reserved.
//

#import "DataBaseHelper.h"
#import "CTPMessage.h"
/**
 *  我现在是添加说说
 */

static DataBaseHelper *helper = nil;

@implementation DataBaseHelper


+(DataBaseHelper *)sharedDataBaseHelper{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        helper = [[DataBaseHelper alloc]init];
        [helper createDataBase];
        [helper createTable];
    });
    return  helper;
}

//创建数据库
- (void)createDataBase{
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *filePath = [doc stringByAppendingPathComponent:@"messages.sqlite"];
    NSLog(@"%@",filePath);
    //创建数据库
    self.db = [FMDatabase databaseWithPath:filePath];
}

//创建表
#warning 注意图片的名称数组，不知道怎么处理

- (void)createTable{
    if ([self.db open]) {
        BOOL result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_message (id integer PRIMARY KEY AUTOINCREMENT, titleId INTEGER, content text,created_at text,imgsArray blob);"];
        if (result) {
            NSLog(@"创建成功");
        }else{
            NSLog(@"创建失败");
        }[self.db close];
    }else{
        NSLog(@"数据库打开失败");
    }
}

//插入操作
- (void)insertMessage:(CTPMessage *)message{
    if ([self.db open]) {
        // img 转 imgData
        NSMutableArray *imgDataArray = [NSMutableArray arrayWithCapacity:5];
        for (UIImage *img in message.imgsArray) {
            NSData *imgData = UIImageJPEGRepresentation(img, 1);
            [imgDataArray addObject:imgData];
        }
        // storePicutreURLs 归档
        NSMutableData * imgArrayData = [NSMutableData dataWithCapacity:1000000];
        NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:imgArrayData];
        //  创建的时间归档
        [archiver encodeObject:imgDataArray forKey:[NSString stringWithString:message.created_at]];
        [archiver finishEncoding];
        
        BOOL result = [self.db executeUpdate:@"INSERT INTO t_message (titleId, content, created_at,imgsArray) VALUES (?,?,?,?);", message.titleId, message.content, message.created_at, imgDataArray[0]];
        if (result) {
            NSLog(@"插入成功");
        }else{
            NSLog(@"插入失败");
        }
        [self.db close];
    }else{
        NSLog(@"数据库打开失败");
    }
}
//删除
- (void)deleteMessage:(CTPMessage *)message{
    if ([self.db open]) {
        BOOL result = [self.db executeUpdate:@"delete from t_message where created_at = ?",message.created_at];
        if (result) {
            NSLog(@"创建成功");
        }else{
            NSLog(@"创建失败");
        }
        [self.db close];
    }else{
        NSLog(@"数据库打开失败");
    }
}
//修改数据
- (void)updateMessage:(CTPMessage *)message
{
    if ([self.db open]) {
        BOOL result = [self.db executeUpdate:@"UPDATE t_message SET titleId = ?,content = ?,created_at= ?,pic_urls= ? WHERE created_at = ?",
                       message.titleId,message.content,message.created_at,message.pic_urls];
        if (result) {
            NSLog(@"修改成功");
        }
        else
        {
            NSLog(@"修改失败");
        } [self.db close];
    }else{
        NSLog(@"数据库打开失败");
    }
}
//查询
- (NSArray *)queryMessage{
    NSMutableArray *arr = [NSMutableArray array];
    if ([self.db open]) {
        FMResultSet *set = [self.db executeQuery:@"SELECT * FROM t_message"];
        while ([set next]) {
            NSInteger titleId = [set intForColumn:@"titleId"];
            NSString *content = [set stringForColumn:@"content"];
            NSString *created_at = [set stringForColumn:@"created_at"];
//            NSString *pic_urls = [set stringForColumn:@"pic_urls"];
            NSMutableData *imgsArray=[set dataForColumn:@"imgsArray"];
            CTPMessage *message = [[CTPMessage alloc]initWithTitleId:titleId content:content created_at:created_at imgsArray:imgsArray];
            [arr addObject:message];
        }
    }
    return arr;
}

// 根据ID查询笔记
- (NSArray *)selectMessage{
    FMResultSet *result = [self.db executeQuery:@"SELECT * FROM t_message"];
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:5];
    while ([result next]) {
        
        CTPMessage *message = [[CTPMessage alloc]init];
        message.created_at = [result stringForColumn:@"created_at"];
        message.content = [result stringForColumn:@"content"];
        NSData *imgArrayData = [result dataForColumn:@"imgsArray"];
        
        // imgArray反归档
        NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:imgArrayData];
        NSMutableArray *imgDataArray = [unarchiver decodeObjectForKey:message.created_at];
        [unarchiver finishDecoding];
        
        // imgData 转 img
        NSMutableArray *imgArray = [NSMutableArray arrayWithCapacity:5];
        for (NSData *data in imgDataArray) {
            UIImage *img = [UIImage imageWithData:data];
            [imgArray addObject:img];
        }
        
        message.imgsArray = imgArray;
        
        [array addObject:message];
    }
    [result close];
    
    if (array.count == 0) {
        NSLog(@"没有查到!");
        return nil;
    }
    
    return array;
}


@end
